import React, { useEffect, useState, useRef } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';

const MapComponent = () => {
    // 状态管理
    const [map, setMap] = useState(null);
    const [position, setPosition] = useState(null);
    const [address, setAddress] = useState('');
    const [totalDistance, setTotalDistance] = useState(0);  // 总移动距离（米）

    // 使用ref存储定位路径（避免状态更新异步问题）
    const pathRef = useRef([]);

    // 安全配置（必须）
    useEffect(() => {
        window._AMapSecurityConfig = {
            securityJsCode: "83bc0e288beb6232bc0336b1901f36ba"  // 替换为你的安全密钥
        };
    }, []);

    // 地图初始化与定位逻辑
    useEffect(() => {
        let geolocation = null;
        let mapInstance = null;
        let watchId = null;

        AMapLoader.load({
            key: '1eb29d5bd147edac9a898c41ff00cbba',  // 替换为你的API Key
            version: '2.0',
            plugins: ['AMap.Geolocation', 'AMap.Geocoder', 'AMap.GeometryUtil']  // 确保包含几何计算插件
        }).then((AMap) => {
            // 创建地图实例
            mapInstance = new AMap.Map('map-container', {
                zoom: 15,
                resizeEnable: true
            });

            // 配置定位插件
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,    // 高精度定位
                timeout: 10000,             // 超时时间10秒
                showMarker: true,           // 显示定位标记
                showButton: true,           // 显示定位按钮
                buttonPosition: 'RB',       // 按钮在右下角
                zoomToAccuracy: true,       // 自动调整视野
                timeInterval: 5000,         // 每5秒定位一次
                distanceInterval: 1      // 位置变化超过10米触发
            });

            // 添加定位控件到地图
            mapInstance.addControl(geolocation);

            // 启动持续定位监听
            watchId = geolocation.watchPosition((status, result) => {
                if (status === 'complete') {
                    const newPosition = result.position;

                    // 更新当前位置状态
                    setPosition(newPosition);

                    // 自动居中地图
                    mapInstance.setCenter(newPosition);

                    // 计算移动距离
                    const currentPath = pathRef.current;
                    if (currentPath.length > 0) {
                        const lastPosition = currentPath[currentPath.length - 1];
                        const distance = AMap.GeometryUtil.distance(lastPosition, newPosition);
                        setTotalDistance(prev => prev + distance);
                    }
                    pathRef.current = [...currentPath, newPosition];

                    // 逆地理编码获取地址信息
                    new AMap.Geocoder().getAddress(newPosition, (status, geoResult) => {
                        if (status === 'complete' && geoResult.info === 'OK') {
                            const addr = geoResult.regeocode;
                            // console.log(addr);
                            
                            setAddress([
                                `详细地址: ${addr.formattedAddress};`,
                                `行政区划: ${addr.addressComponent.province} → 
                                ${addr.addressComponent.city} → 
                                ${addr.addressComponent.district} → 
                                ${addr.addressComponent.township} → 
                                ${addr.addressComponent.street}
                                `
                            ].join('\n'));
                        }
                    });
                } else {
                    console.error('定位失败:', result);
                }
            });

            setMap(mapInstance);
        }).catch(error => {
            console.error('地图初始化失败:', error);
        });

        // 清理函数
        return () => {
            if (geolocation && watchId) {
                geolocation.clearWatch(watchId);
            }
            if (mapInstance) {
                mapInstance.destroy();
            }
        };
    }, []);

    return (
        <div style={{ padding: 20 }}>
            <div
                id="map-container"
                style={{
                    width: '100%',
                    height: '400px',
                    boxShadow: '0 2px 6px rgba(0,0,0,0.3)',
                    borderRadius: 8
                }}
            />

            {/* 信息展示面板 */}
            {position && (
                <div style={{ marginTop: 20 }}>
                    <h3>当前位置</h3>
                    <div style={{ lineHeight: 1.8 }}>
                        <p>📌 经纬度: {position.lat.toFixed(6)}, {position.lng.toFixed(6)}</p>
                        <p>🛣️ 累计移动距离: {(totalDistance / 1000).toFixed(2)} 公里</p>
                        <p style={{
                            background: '#f5f5f5',
                            padding: 12,
                            borderRadius: 4
                        }}>
                            {address}
                        </p>
                    </div>
                </div>
            )}
        </div>
    );
};

export default MapComponent;